<template>
  <div class="page-box">
    <el-form :inline="true" :model="searchData" ref="form" label-width="90px">
      <el-form-item label="商品目录">
        <el-select style="width: 200px;" v-model="searchData.primaryCategory" placeholder="请选择一级目录" filterable clearable @change="categorySearch(2)">
          <el-option
            v-for="emall in categoryLv1"
            :key="emall.id"
            :label="emall.categoryName"
            :value="emall.id">
          </el-option>
        </el-select>
        <el-select style="margin-left:10px;width: 200px;" v-model="searchData.secondaryCategory" placeholder="请选择二级目录" filterable clearable @change="categorySearch(3)">
          <el-option
            v-for="emall in categoryLv2"
            :key="emall.id"
            :label="emall.categoryName"
            :value="emall.id">
          </el-option>
        </el-select>
        <el-select style="margin-left:10px;width: 200px;" v-model="searchData.tertiaryCategory" placeholder="请选择三级目录" filterable clearable>
          <el-option
            v-for="emall in categoryLv3"
            :key="emall.id"
            :label="emall.categoryName"
            :value="emall.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品状态">
        <el-select style="margin-left:10px;" v-model="searchData.goodsState" placeholder="请选择商品状态" clearable>
          <el-option
            v-for="state in states"
            :key="state.key"
            :label="state.value"
            :value="state.key">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input v-model="searchData.goodsName" placeholder="请输入商品名称" ></el-input>
      </el-form-item>
      <el-form-item label="商品sku">
        <el-input v-model="searchData.sku" placeholder="请输入商品sku" ></el-input>
      </el-form-item>
      <!-- <el-form-item label="生产地">
        <el-input v-model="searchData.goodsArea" placeholder="请输入生产地" ></el-input>
      </el-form-item> -->
      <el-form-item label="规格型号">
        <el-input v-model="searchData.typeNo" placeholder="请输入规格型号" ></el-input>
      </el-form-item>
      <el-form-item label="包装方式">
        <el-input v-model="searchData.packing" placeholder="请输入包装方式" ></el-input>
      </el-form-item>
      <el-form-item >
        <el-button type="primary" icon="el-icon-search" @click="handleCurrentChange(1)">查询</el-button>
      </el-form-item>

    </el-form>
    <el-row class="page-box-operation" type="flex" justify="end">
      <el-button
        style="margin-right: 10px;"
        type="primary" size="small"
        @click="exportTemplate">
        下载模板
      </el-button>
<!--      <a href="'/static/导入商品模板.xlsx" download="导入商品模板">下载模板</a>-->
      <el-upload
        style="padding-right: 10px;"
        :headers="fileConfig.headers()"
        :action="uploadUrl"
        multiple
        :limit="1"
        :file-list="fileList"
        :show-file-list="false"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        accept=".xlsx, .xls"
        :before-upload="beforeUpload"
        :on-exceed="handleExceed">
        <el-button class="upload-btn" type="primary" size="small" v-loading.fullscreen.lock="loading">导入商品</el-button>
      </el-upload>
      <el-button  type="primary" @click="toAddView" size="small">添加</el-button>
      <el-button  type="primary" @click="doIt(1)" size="small">批量上架</el-button>
      <el-button  type="primary" @click="doIt(2)" size="small">批量下架</el-button>
    </el-row>

    <el-table
        border
        :data="tableData"
        :max-height="maxHeightNow"
        style="width: 100%"
		  @selection-change="handleSelectionChange"
        >
	  <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="tertiaryCategoryName" label="商品目录"  width="110"></el-table-column>
      <el-table-column prop="brandName"  label="商品品牌"  min-width="140" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column prop="typeNo"  label="规格型号"  min-width="140" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column label="商品名称" prop="goodsName" min-width="140" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column label="商品sku" prop="sku" min-width="140" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column label="商品状态" width="80" >
        <template slot-scope="scope">
          {{statesMap[scope.row.goodsState]}}
        </template>
      </el-table-column>
      <el-table-column prop="agreementPrice" label="市场价格"  width="100"></el-table-column>
      <el-table-column prop="excludeTaxPrice" label="未税价格"  width="100"></el-table-column>
      <el-table-column prop="taxRate" label="税率"  width="100"></el-table-column>
      <el-table-column prop="goodsStock" label="库存"  width="100">
		    <template slot-scope="scope">
		      <el-input v-model="scope.row.goodsStock" @change="changeStock(scope.row)" />
		    </template>
	  </el-table-column>
      <el-table-column prop="saleUnit" label="计量单位"  width="100"></el-table-column>
      <el-table-column prop="packing" label="包装方式"  width="100"></el-table-column>
      <el-table-column prop="gmtCreate" label="记录时间"  width="160"></el-table-column>
      <el-table-column prop="gmtModify" label="最后修改时间"  width="160"></el-table-column>
      <el-table-column label="操作" fixed="right" width="210" >
        <template slot-scope="scope">
          <el-button  type="warning" size="mini" v-show="scope.row.goodsState != 'COMMIT'" @click="updateDialog(scope.row)">修改</el-button>
          <el-button  type="primary" v-show="scope.row.goodsState == 'PASS'" size="mini" @click="downState(scope.row)">下架</el-button>
          <el-button  type="primary" size="mini" @click="infoDialog(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size=pageSize
        layout="total, sizes, prev, pager, next, jumper"
        :total=totalPage>
    </el-pagination>

    <el-dialog title="商品上下架历史记录" :visible.sync="dialogVisible" width="85%" >
      <el-table border :data="logTableData" style="width: 100%">
        <el-table-column label="商品状态" min-width="16%" >
          <template slot-scope="scope">
            {{statesMap[scope.row.goodsState]}}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="时间"  min-width="16%">
          <template slot-scope="scope">
            {{scope.row.createTime.replace("T"," ")}}
          </template>
        </el-table-column>
        <el-table-column prop="goodsPrice" label="市场参考价" min-width="16%"></el-table-column>
        <el-table-column label="链接" min-width="16%">
            <el-link :underline="false" @click="gotoDeatil(itemId)">点击跳转</el-link>
        </el-table-column>
        <el-table-column prop="describle" label="原因" min-width="36%"></el-table-column>
      </el-table>
      <el-pagination
        @size-change="logHandleSizeChange"
        @current-change="logHandleCurrentChange"
        :current-page="logCurrentPage"
        :page-size=logPageSize
        layout="total, sizes, prev, pager, next, jumper"
        :total=logTotalPage>
      </el-pagination>
    </el-dialog>
    <el-dialog :title="failTitle" :visible.sync="dialogImportVisible" width="60%">
      <p style="padding: 5px; box-sizing: border-box;" v-for="(v,i) in errImport" :key="i">{{v}}</p>
    </el-dialog>
  </div>
</template>

<script>
  // eslint-disable-next-line
  const baseUrl = process.env.VUE_APP_BASE_API
  // 上传文件
  import fileUpdata from '@/api/file.config'
  import {
    queryGodCategoryZtreeAsyn,
    goodsItemManageList,
    itemStateHisList,
    postGoodsState,
	saveOrUpdateProducts,
	getSupplierGoodsInfo,
	updateGoodsItem
  } from '@/api/supplier.api';
  import { setGoodsState,systemHis } from '@/api/admin.api'
  export default {
    name: 'e-commerce-putaway',
    components: {},
    data() {
      return {
        loading: false,
        failTitle: '',
        searchData:{
          secondaryCategory:"",
          tertiaryCategory:"",
        },
        categoryLv1:[],
        categoryLv2:[],
        categoryLv3:[],
        states:[
           {
            key:"",
            value:"全部"
          },
          {
            key:"UNCOMMIT",
            value:"未提交"
          },
          {
            key:"COMMIT",
            value:"已提交"
          },
          {
            key:"PASS",
            value:"正常上架"
          },
          {
            key:"RETURN",
            value:"审核退回"
          },
          {
            key:"DOWN",
            value:"商品下架"
          },
        ],
        statesMap:{
          "UNCOMMIT":"未提交",
          "COMMIT":"已提交",
          "PASS":"正常上架",
          "RETURN":"审核退回",
          "DOWN":"商品下架"
        },

        tableData:[],
        currentPage:1,
        pageSize:10,
        totalPage:0,

        dialogVisible:false,
        itemId:"",
        logTableData:[], //上下架记录列表
        logCurrentPage:1,
        logPageSize:10,
        logTotalPage:0,
        // 附件列表
        fileList: [],
        fileConfig: fileUpdata,
        uploadUrl: `${baseUrl}/api/goodsItem/manage/uploadGoodsItem`,
        dialogImportVisible: false,
        // 导入错误信息
        errImport: []
      }
    },
    watch: {},
    computed: {
      maxHeightNow () {
        const height = window.innerHeight
        return height -  320
      }
    },
    created() {
      this.categorySearch(1);
      this.onSearch();
    },
    mounted() {
    },
    methods: {
		changeStock(row){
			updateGoodsItem({
				id:row.id,
				goodsStock:row.goodsStock
			}).then(res => {
			  this.$message({
			    type: 'success',
			    message: '操作成功!'
			  });
			  this.onSearch ()
			})
		},
		doIt(t){
			var that = this;
			// this.multipleSelection 
			var arr = this.multipleSelection;
			if(arr.length<=0){
				return this.$message({
					type: 'error',
					message: '请选择操作行!'
				});
			}
			var ids = [];
			for (var i = 0; i < arr.length; i++) {
				ids.push(arr[i].id);
			}
			
			console.log(ids);
			if(t == 1){
				//上
				this.$confirm('是否确定上架此商品?', '提示', {
				  confirmButtonText: '确定',
				  cancelButtonText: '取消',
				  type: 'warning'
				}).then(() => {
				    for (var i = 0; i < arr.length; i++) {
						that.getIt(ids[i]);
				    }
				});
			}else{
				//下
				this.$confirm('是否确定下架此商品?', '提示', {
				  confirmButtonText: '确定',
				  cancelButtonText: '取消',
				  type: 'warning'
				}).then(() => {
				  for (var i = 0; i < ids.length; i++) {
				  	that.downIt(ids[i],arr[i]);
				  }
				});
			}
		},
		getIt(t){
			getSupplierGoodsInfo({
				id:t
			}).then(res => {
			  this.upIt (res)
			})
		},
		downIt(t,row){
			postGoodsState(t,"DOWN").then(res => {
			  this.$message({
			    type: 'success',
			    message: '操作成功!'
			  });
			  row.goodsState = 'DOWN';
			  this.changeHistory(row);
			  this.onSearch ()
			})
		},
		upIt(t){
			t.isCommit = true;
			saveOrUpdateProducts(t).then(res => {
			  this.$message({
			    type: 'success',
			    message: '操作成功!'
			  });
			  this.onSearch ()
			})
		},
		handleSelectionChange(val) {
		  this.multipleSelection = val;
		  console.log(val)
		},
      // 提交检测判断
      handleExceed(files, fileList) {
        this.$message.warning(`最多可同时上传 1 个附件，您已超限`)
      },
      beforeUpload(file) {
        this.loading = true
        const isLt500M = file.size / 1024 / 1024 < 500
        if (!isLt500M) {
          this.$message.error('上传附件大小不能超过 500MB!')
        }
        return isLt500M
      },
      // 文件上传成功
      handleUploadSuccess(res, file) {
        this.fileList = []
        this.loading = false
        switch (Number(res.code)) {
          case 0: // 导入成功
            this.$message.success('导入成功！');
            // 刷新列表页
            this.onSearch();
            break
          case 1: // 解析失败
            this.exportFail(res);
            break
          case 2: // 部分图片导入失败
            this.exportFail(res);
            this.onSearch();
            break
          default:
            break
        }
      },
      // 导入失败信息
      exportFail(res) {
        this.errImport = res.data;
        this.failTitle = res.msg;
        this.dialogImportVisible = true;
      },
      // 文件上传失败
      handleUploadError(res, file) {
        let result = JSON.parse(res.message)
        this.$message.warning(result.msg||'上传失败！')
      },
      categorySearch(level){
        let parentId = null;
        if(level==2){
          this.categoryLv3=[];
          this.searchData.secondaryCategory="";
          this.searchData.tertiaryCategory="";

          if(!this.searchData.primaryCategory){
            this.categoryLv2=[];
            return;
          }
          parentId = this.searchData.primaryCategory;
        }else if(level==3){
          this.searchData.tertiaryCategory="";
          if(!this.searchData.secondaryCategory){
            this.categoryLv3=[];
            return;
          }
          parentId = this.searchData.secondaryCategory;
        }

        queryGodCategoryZtreeAsyn(parentId,"1").then( res =>{
          if(level==1){
            this.categoryLv1=res;
          }else if(level==2){
            this.categoryLv2=res;
          }else if(level==3){
            this.categoryLv3=res;
          }
        })

      },

      gotoDeatil(id){
        window.open('./detail?id='+id);
      },

      onSearch(){
        this.searchData.current = this.currentPage;
        this.searchData.size = this.pageSize;
        this.searchData.goodsSource = 'LOCAL_SUPPLIER';
       goodsItemManageList(this.searchData).then( res =>{
          this.tableData = res.content
          this.totalPage = res.totalElements
        })


      },
      handleSizeChange(val) {
        this.pageSize = val
        this.currentPage = 1
        this.onSearch()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.onSearch()
      },

      openDialog(row){
        this.logCurrentPage=1;
        this.logPageSize=10;
        this.logTotalPage=0;
        this.itemId = row.id;

        this.searchHis();
      },

      searchHis(){
        const params = {
          current : this.logCurrentPage,
          size : this.logPageSize
        }
        itemStateHisList(this.itemId,params).then( res =>{
          this.logTableData = res.records
          this.logTotalPage = res.total
          if(!this.dialogVisible){
            this.dialogVisible=true;
          }
        })
      },

      logHandleSizeChange(val) {
        this.logPageSize = val
        this.logCurrentPage = 1
        this.searchHis()
      },
      logHandleCurrentChange(val) {
        this.logCurrentPage = val
        this.searchHis()
      },

      downState(row){
        this.$confirm('是否确定下架此商品?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          postGoodsState(row.id,"DOWN").then(res => {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
			row.goodsState = 'DOWN';
			this.changeHistory(row);
            this.onSearch ()
          })

        });

      },
	  changeHistory(row){
	  	  row.fkItemId = row.id;
	  	  row.goodsPrice = row.agreementPrice;
	  	  row.supplierName = row.supplierName;
	  	  row.supplierType = 1;
	  	  systemHis(row).then(res => {
	  	  })
	  },
      toAddView(){
        this.$router.push("/supplier-commerce-putawayt-add");
      },
      // 导入下载模板
      exportTemplate() {
        const downLoadEle = document.createElement('a')
        const href = '/static/ProductTemplate.xlsx'
        downLoadEle.href = href
        downLoadEle.download = '导入商品模板.xlsx'
        document.body.appendChild(downLoadEle)
        downLoadEle.click()
        document.body.removeChild(downLoadEle)
        // 当加载完成后释放对象URL.
        window.URL.revokeObjectURL(href)
      },
      updateDialog(row){
        this.$router.push({path:"/supplier-commerce-putawayt-add",query: {id:row.id}});
      },
      infoDialog(row){
        this.$router.push({path:"/supplier-commerce-putawayt-add",query: {id:row.id,info:'info'}});
      }
    }
  }
</script>

<style scoped lang="scss">
  .page-box {
    padding: 20px;
    background: white;
    .form-operation {
      text-align: right;
      .el-form-item {
        margin-right: 0;
      }
    }
    .el-pagination {
      padding: 20px;
      text-align: right;
    }
    &-tool {
      // text-align: right;
      padding-bottom: 20px;
    }
    &-operation {
      padding-bottom: 10px;
    }
  }
  .cell-content {
    width: 200px;
    min-height: 20px;
    max-height: 200px;
    overflow-y: auto;
  }
  .overflow {
    width: 118px;
    overflow:hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    -o-text-overflow:ellipsis;
  }

</style>

<style lang="css">

  .el-tooltip__popper,.el-tooltip__popper.is-dark{
    background: #FFFFFF;
    max-width: 400px;
    border-radius: 4px;
    border: 1px solid #e6ebf5;
    padding: 12px;
    color: black;
    line-height: 180%;
    -webkit-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  .el-tooltip__popper[x-placement^=top] .popper__arrow {
    /*border-top-color: rgba(0,0,0,0.4);*/
    bottom: -6px;
    left: 50%;
    margin-right: 3px;
    border-top-color: #FFFFFF;
    border-bottom-width: 0;
    -webkit-filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
    filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
  }
  .el-tooltip__popper[x-placement^=top] .popper__arrow:after {
    /*border-top-color: rgba(0,0,0,0.4);*/
    position: absolute;
    display: block;
    width: 0;
    height: 0;
    border-color: transparent;
    border-style: solid;
    /*filter:alpha(opacity=50);
    -moz-opacity:0.5;
    -khtml-opacity: 0.5;
    opacity: 0.5;*/
  }
</style>
